package servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.*;

/**
 * Servlet implementation class DeleteUser
 */
@WebServlet("/DeleteUser")
public class DeleteUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = (request.getParameter("user_name")).trim();
		
		Map<String, String> messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);		
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			umq.deleteUser(username);	
			messages.put("delete_user_msg", "<span class=\"message success\">User Deleted.</span>");
			response.setHeader("Cache-Control", "no-cache");
			request.getRequestDispatcher("admin.jsp").forward(request, response);	
		}
		catch (Exception e) {
			messages.put("delete_user_msg", "<span class=\"message error\">User could not be deleted.</span>");
			response.sendError(500);
			request.getRequestDispatcher("admin.jsp").forward(request, response);				
		    e.printStackTrace();
		}
	}

}
